package com.ruoyi.customer.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.domain.TRevieweCooperate;
import com.ruoyi.customer.domain.bo.CustomerBo;
import com.ruoyi.customer.domain.bo.TRevieweBo;
import com.ruoyi.customer.domain.bo.TRevieweInfoBo;
import com.ruoyi.customer.domain.bo.WithdrawBo;
import com.ruoyi.customer.domain.vo.CustomerVo;
import com.ruoyi.customer.domain.vo.TRevieweInfoVo;
import com.ruoyi.customer.domain.vo.TRevieweVo;
import com.ruoyi.customer.domain.vo.WithdrawInfoVo;
import com.ruoyi.customer.mapper.TRevieweCooperateMapper;
import com.ruoyi.customer.service.ICustomerService;
import com.ruoyi.customer.service.ITRevieweInfoService;
import com.ruoyi.system.service.ITFileInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 再审件
 *
 * @author zr
 * @date 2023-08-02
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/customer/revieweInfo")
public class TRevieweInfoController extends BaseController {

    private final ITRevieweInfoService iTRevieweInfoService;
    private final ITFileInfoService fileInfoService;
    private final ICustomerService customerService;
    private final TRevieweCooperateMapper cooperateMapper;

//    /**
//     * 查询再审件列表
//     */
//    @SaCheckPermission("customer:revieweInfo:list")
//    @GetMapping("/list")
//    public TableDataInfo<TRevieweInfoVo> list(TRevieweInfoBo bo, PageQuery pageQuery) {
//        return iTRevieweInfoService.queryPageList(bo, pageQuery);
//    }


    /**
     * 查询再审件列表
     */
    //@SaCheckPermission("customer:revieweInfo:list")
    @GetMapping("/list")
    public TableDataInfo<TRevieweVo> list(TRevieweBo bo, PageQuery pageQuery) {
        return iTRevieweInfoService.queryPageCustomerList(bo, pageQuery);
    }

    /**
     * 查询再审件列表
     */
    //@SaCheckPermission("customer:revieweInfo:list")
    @GetMapping("/customerList")
    public TableDataInfo<CustomerVo> customerList(CustomerBo bo, PageQuery pageQuery) {
        return iTRevieweInfoService.revieweInfoCustomerList(bo, pageQuery);
    }

    /**
     * 导出再审件列表
     */
    @SaCheckPermission("customer:revieweInfo:export")
    @Log(title = "再审件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TRevieweInfoBo bo, HttpServletResponse response) {
        List<TRevieweInfoVo> list = iTRevieweInfoService.queryList(bo);
        ExcelUtil.exportExcel(list, "再审件", TRevieweInfoVo.class, response);
    }

    /**
     * 获取再审件详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("customer:revieweInfo:query")
    @GetMapping("/{id}")
    public R<TRevieweInfoVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        TRevieweInfoVo revieweInfoVo = Optional.ofNullable(iTRevieweInfoService.queryById(id))
                .orElseThrow(() -> new BaseException("审件信息没有找到"));
        revieweInfoVo.setHtList(fileInfoService.fileList(String.valueOf(id), "reviewe-file"));
        Optional.ofNullable(customerService.queryById(revieweInfoVo.getCustomerId()))
                .ifPresent(it -> {
                            revieweInfoVo.setRemark(it.getBz());
                        }
                );
        LambdaQueryWrapper<TRevieweCooperate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TRevieweCooperate::getRevieweId, id);
        List<TRevieweCooperate> cooperates = cooperateMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(cooperates)) {
            revieweInfoVo.setCooperateList(cooperates);
        }
        String withdrawInfo = revieweInfoVo.getWithdrawInfo();
        if (StringUtils.isNotBlank(withdrawInfo)) {
            List<WithdrawInfoVo> withdrawInfoVos = JsonUtils.parseArray(withdrawInfo, WithdrawInfoVo.class);
            if (!CollectionUtils.isEmpty(withdrawInfoVos)) {
                revieweInfoVo.setWithdrawInfoVo(withdrawInfoVos.stream().sorted(Comparator.comparing(WithdrawInfoVo::getCreateTime).reversed()).map(it -> {
                    return it.getCreateBy() + "--" + it.getCreateTime() + " 原因：" + it.getReason();
                }).collect(Collectors.joining("</br>")));
            }
        }
        return R.ok(revieweInfoVo);
    }

    /**
     * 新增再审件
     */
    @SaCheckPermission("customer:revieweInfo:add")
    @Log(title = "再审件", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TRevieweInfoBo bo) {
        return toAjax(iTRevieweInfoService.insertByBo(bo));
    }

    /**
     * 修改再审件
     */
    //@SaCheckPermission("customer:revieweInfo:edit")
    @Log(title = "再审件", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TRevieweInfoBo bo) {
        return toAjax(iTRevieweInfoService.updateByBo(bo));
    }

    /**
     * 删除再审件
     *
     * @param ids 主键串
     */
    @SaCheckPermission("customer:revieweInfo:remove")
    @Log(title = "再审件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTRevieweInfoService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    @PostMapping("/withdraw")
    public R withdraw(@RequestBody WithdrawBo withdrawBo) {
        iTRevieweInfoService.withdrawOperator(withdrawBo);
        return R.ok();
    }
}
